package com.llkj.contractmanagement.utils;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;


import com.llkj.contractmanagement.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class UpdateVersionService {
	private static final int DOWN = 1;
	private static final int DOWN_FINISH = 0;
	private static final int DOWN_ERROR = 2;
	public static boolean cancelUpdate = false;
	private String fileSavePath;
	private int progress;
	private Context context;
	private String urlapk;// apk的下载地址
	private NotificationManager notificationManager;
	private Notification notification;
	private NotificationCompat.Builder builder;
	private String apkName = "daijia_user.apk";
	private Handler handler = new Handler() {
		@SuppressLint("NewApi")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case DOWN:
				// 改变通知栏
				if (progress % 5 == 0) {
					builder.setProgress(100, progress, false).setContentText(
							progress + "%");
					notificationManager.notify(1000, builder.build());
				}
				break;
			case DOWN_FINISH:	
				File apkfile = new File(fileSavePath, apkName);
				if (!apkfile.exists()) {
					return;
				}
				notificationManager.cancel(1000);
				installAPK(apkfile);
				break;
			case DOWN_ERROR:
				notification = builder.setContentTitle("吾义泰租车")
						.setContentText("下载失败").build();
				notification.flags = Notification.FLAG_AUTO_CANCEL;
				notificationManager.notify(1000, notification);
				break;
			default:	
				break;
			}
		}

	};

	public UpdateVersionService(Context context, String url) {
		this.context = context;
		this.urlapk = url;
		createNotification();
	}

	private void installAPK(File apkfile) {
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		context.startActivity(i);
	}

	/**
	 * 实例化通知栏
	 */
	public void createNotification() {
		builder = new NotificationCompat.Builder(context);
		builder.setContentTitle("正在下载：吾义泰租车");
		builder.setSmallIcon(R.mipmap.ic_launcher);
		builder.setAutoCancel(false).setOngoing(true);
		notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		notificationManager.notify(1000, builder.build());
		new downloadApkThread().start();
	}

	public class downloadApkThread extends Thread {

		@Override
		public void run() {
			super.run();
			Message message;
			try {
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					fileSavePath = Utils.getAppDir(context);
					URL url = new URL(urlapk);
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setReadTimeout(5 * 1000);// 设置超时时间
					conn.setRequestMethod("GET");
					conn.setRequestProperty("Charser",
							"GBK,utf-8;q=0.7,*;q=0.3");
					int length = conn.getContentLength();
					InputStream is = conn.getInputStream();
					File file = new File(fileSavePath);
					if (!file.exists()) {
						file.mkdirs();
					}
					File apkFile = new File(fileSavePath, apkName);
					FileOutputStream fos = new FileOutputStream(apkFile);
					int len = 0;
					int total = 0;
					byte buf[] = new byte[1024];
					while ((len = is.read(buf)) != -1) {
						fos.write(buf, 0, len);
						total += len;
						progress = (int) (((float) total / length) * 100);
						message = handler.obtainMessage(DOWN);
						handler.sendMessage(message);
					}
					fos.close();
					is.close();
					message = handler.obtainMessage(DOWN_FINISH);// 下载完成
					handler.sendMessage(message);
				}
			} catch (MalformedURLException e) {
				message = handler.obtainMessage(DOWN_ERROR);// 下载失败
				handler.sendMessage(message);
				e.printStackTrace();
			} catch (IOException e) {
				message = handler.obtainMessage(DOWN_ERROR);// 下载失败
				handler.sendMessage(message);
				e.printStackTrace();
			}
		}
	}
}
